package com.muapet.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.muapet.model.Account;
import com.muapet.model.Order;
import com.muapet.model.User;
import com.muapet.model.other.AddressInfo;
import com.muapet.model.other.sendInfo;
import com.muapet.service.IOrderService;
import com.muapet.service.IUserService;
import com.muapet.util.Md5Utils;

@Controller
@RequestMapping("/order")
public class OrderController {
	private IUserService userService;
	private IOrderService orderService;

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/newOrder")
	@ResponseBody
	public String newOrder(Integer petId, AddressInfo addressInfo,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else {

			Integer id = orderService.addOrder(petId, loginUser.getId(),
					addressInfo);
			if (id != null && id > 0) {
				resultMap.put("msg", "success");
				resultMap.put("orderId", id);
			} else if (id != null && id == -1) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "宠物已被购买，来晚一步！");
			} else if (id != null && id == -2) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "该宠物不存在，请查看是否已被删除！");
			} else if (id != null && id == -3) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "余额不足请前往充值！");
			} else if (id != null && id == -4) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "自己的宠物不能购买！");
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "出了点小问题");
			}
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping("/myOrders")
	public ModelAndView myOrders(HttpServletRequest request) {
		ModelAndView mav;
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "请先登录");
		} else {
			mav = new ModelAndView("myorders");
		}
		return mav;
	}

	@RequestMapping("/payOrder")
	public ModelAndView payOrder(Integer id, HttpServletRequest request) {
		ModelAndView mav;
		Order order = orderService.findById(id);
		if (order == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到该订单");
		} else {
			mav = new ModelAndView("payOrder");
			mav.addObject("order", order);
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/pay")
	@ResponseBody
	public String pay(Integer orderId, String password,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String pwdMd5 = Md5Utils.md5(password);
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else {
			Order order = orderService.findById(orderId);
			if (order == null) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "找不到该订单");
			} else {
				if (loginUser.getId().equals(order.getBuyerId())) {
					Account account = userService.findAccountByUserId(loginUser
							.getId());
					if (account == null
							|| account.getBalance() < order.getPrice()) {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "余额不足，请前往我的钱包充值");
					} else if (!account.getPayPassword().equals(pwdMd5)) {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "支付密码错误");
					} else if (order.getState() == Order.ORDER_STATE_NEW) {
						userService.updateAccountByUserId(loginUser.getId(),
								order.getPrice(), false);
						orderService.pay(orderId);
						resultMap.put("msg", "success");
					} else {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "订单状态异常");
					}
				} else {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "不是自己买入的订单哦");
				}
			}
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping("/sendOrder")
	public ModelAndView sendOrder(Integer id, HttpServletRequest request) {
		ModelAndView mav;
		Order order = orderService.findById(id);
		if (order == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到该订单");
		} else {
			mav = new ModelAndView("sendOrder");
			mav.addObject("order", order);
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/send")
	@ResponseBody
	public String send(Integer orderId, sendInfo sendInfo,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else {
			Order order = orderService.findById(orderId);
			if (order == null) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "找不到该订单");
			} else {
				if (loginUser.getId().equals(order.getSellerId())) {
					if (order.getState() == Order.ORDER_STATE_TOSEND) {
						orderService.send(orderId, sendInfo);
						resultMap.put("msg", "success");
					} else {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "订单状态异常");
					}
				} else {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "不是自己出售的订单哦");
				}
			}
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/receive")
	@ResponseBody
	public String receive(Integer orderId, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else {
			Order order = orderService.findById(orderId);
			if (order == null) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "找不到该订单");
			} else {
				if (loginUser.getId().equals(order.getBuyerId())) {
					if (order.getState() == Order.ORDER_STATE_TORECEIVE) {
						orderService.receive(orderId);
						userService.updateAccountByUserId(order.getSellerId(),
								order.getPrice(), true);
						resultMap.put("msg", "success");
					} else {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "订单状态异常");
					}
				} else {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "不是自己买入的订单哦");
				}
			}
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listMyOrder")
	@ResponseBody
	public String listMyOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else {
			List<Order> orderList = orderService.listOrdersByUserId(loginUser
					.getId());
			resultMap.put("msg", "success");
			resultMap.put("orderList", orderList);
			resultMap.put("userId", loginUser.getId());
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}
}
